<template>
  <nav-bar>
    <template v-slot:left></template>
    <template v-slot:default>用户注册</template>
    <template v-slot:right></template>
  </nav-bar>

  <div style="margin-top:50px">
    <img src="~assets/images/logo.png" width="100" alt="">
  </div>
  <van-form @submit="onSubmit">
    <van-field
        v-model="name"
        name="昵称"
        label="昵称"
        placeholder="昵称"
        :rules="[{ required: true, message: '请填写昵称' }]"
    />
    <van-field
        v-model="email"
        name="邮箱"
        label="邮箱"
        placeholder="邮箱"
        :rules="[{ required: true, message: '请填写邮箱' }]"
    />
    <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
    />
    <van-field
        v-model="password_confirmation"
        type="password"
        name="确认密码"
        label="确认密码"
        placeholder="确认密码"
        :rules="[{ required: true, message: '请确认密码' }]"
    />
    <div style="margin: 16px;text-align:left">
      <a href="javascript:" style="color:#42b983" @click="$router.push({name: 'Login'})">已有账号，立即登录</a>
    </div>
    <div style="margin: 16px;">
      <van-button round block type="success" native-type="submit">提交</van-button>
    </div>
  </van-form>
</template>

<script>
import {reactive, toRefs} from "vue"
import {useRouter} from 'vue-router'

import {Notify, Toast} from 'vant'

import NavBar from "components/common/navbar/NavBar";
import {register} from "network/user";

export default {
  name: "Register",
  components: {
    NavBar,
  },

  setup() {
    const router = useRouter()
    const userinfo = reactive({
      name: '',
      email: '',
      password: '',
      password_confirmation: '',
    })

    const onSubmit = () => {
      if (userinfo.password !== userinfo.password_confirmation)
        return Notify('两次密码不一致')
      register(userinfo).then(res => {
        if (res.status === 201) {
          Toast.success('注册成功')
          setTimeout(() => router.push({name: 'Login'}), 1000)
        }
        userinfo.password = '';
        userinfo.password_confirmation = '';
      })
    }
    return {
      ...toRefs(userinfo), onSubmit
    }
  }
}
</script>

<style scoped>

</style>